package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.SetmealService;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

/*
* 套餐管理
*/
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    //JedisPool操作Redis服务（清理垃圾图片）
    @Autowired
    private JedisPool jedisPool;
    //文件上传
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
//获取文件原先的后缀
        String originalFilename = imgFile.getOriginalFilename();//原始文件名
        int i = originalFilename.lastIndexOf(".");//以"."截取
        String substring = originalFilename.substring(i - 1);

        //随机产生的字符串+文件原先的后缀
        String fileName = UUID.randomUUID().toString() + substring;

        try {
            //七牛上传
            QiniuUtils.upload2Qiniu(imgFile.getBytes(), fileName);

           jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES, fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
        return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, fileName);
    }

    @Reference//远程调用,查找服务
    private SetmealService setmealService;

    //新建添加表单提交
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds) {

        try {
            setmealService.add(setmeal, checkgroupIds);
        }catch (Exception e){
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }
    //套餐的分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return setmealService.pageQuery(queryPageBean);

    }
}